import java.net.*;
import java.io.*;
import java.util.*;

import javax.net.ssl.*;
import javax.xml.soap.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.*;

import java.security.cert.Certificate;
import java.security.NoSuchAlgorithmException;

public class AcessarURL {
    // Declaração de Variáveis
    private static Proxy proxy;

    // FUNÇÕES
    private static void testProxy() {
        try {
            System.setProperty("java.net.useSystemProxies","true");
            List l = ProxySelector.getDefault().select( new URI("http://www.yahoo.com/"));
            for (Iterator iter = l.iterator(); iter.hasNext(); ) {

                proxy = (Proxy) iter.next();
                //System.out.println("proxy hostname : " + proxy.type());

                InetSocketAddress addr = (InetSocketAddress) proxy.address();

                if(addr == null) {
                    System.out.println("Sem Proxy");
                } else {
                    SocketAddress enderecoProxy = new InetSocketAddress("192.168.1.1",  3128);
                    proxy = new Proxy(Proxy.Type.HTTP, enderecoProxy);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Util a = new Util();// Inicia Clase com as funções Uteis
        testProxy();// Testa se existe Proxy configurado.
        
        
        //System.out.println( ts.Descricao() );
        

        String urlName = "http://e-gov.betha.com.br/e-nota-contribuinte-ws/recepcionarLoteRps?wsdl";//"http://www.betha.com.br/e-nota-contribuinte-ws";//
        // Create a trust manager that does not validate certificate chains

        try {

            HttpURLConnection url;
            int status;  

            URL caminho = new URL( urlName );  

            // conexão  
            if (proxy == null){
                url = ( HttpURLConnection ) caminho.openConnection();
            }
            else{
                url = ( HttpURLConnection ) caminho.openConnection( proxy );
            }

            url.setDoOutput( true );
            url.connect();
            //status = url.getResponseCode();

            /*BufferedWriter out = new BufferedWriter( new OutputStreamWriter( url.getOutputStream( ) ) );
            BufferedReader in = new BufferedReader( new FileReader( "LoteRps_Remessa_857465138841809.xml" ) );

            String line = null;
            String docUrl = "";

            while( (line = in.readLine()) != null ){
                out.write( line, 0, line.length());
                docUrl = docUrl + line;
            }*/
            System.out.println( url.getRequestMethod() );

            /*out.close();
            in = new BufferedReader( new InputStreamReader( url.getInputStream() ) );

            line = null;
            docUrl = "";

            while( (line = in.readLine()) != null ){
                out.write( line, 0, line.length());
                docUrl = docUrl + line;
            }
            System.out.println(docUrl);

            in.close();*/

            url.disconnect();
            //System.out.println(status);

            /*DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = a.stringToDom( docUrl );
            doc.getDocumentElement().normalize();

            //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nList = doc.getElementsByTagName( doc.getDocumentElement().getNodeName() );

            //System.out.println(nList.getLength());

            DOMSource domSource = new DOMSource(doc);
            StreamResult sr = new StreamResult(new File("resultadoAcesso.xml"));
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(domSource, sr);*/

        }catch (MalformedURLException e){
            System.out.println("Erro ao criar URL. Formato inválido.");
            System.exit(1);
        }catch (IOException e2) {
            System.out.println("Erro ao acessar URL: ");
            e2.printStackTrace();
            //System.exit(1);
        }catch (Exception ex) {
            System.out.println("Erro Exception: ");
            ex.printStackTrace();

        }

        /*try {

        } catch (Exception ex) {
        System.out.println("Erro SOAP: ");
        ex.printStackTrace();
        }*/
    }
}

/*String endereco = "http://192.168.1.1";//www.cratus.net.br
try {  
HttpURLConnection url;  

int status;  

SocketAddress enderecoProxy = new InetSocketAddress("servidor",  1234);  

Proxy proxy = new Proxy(Proxy.Type.HTTP, enderecoProxy);  

URL caminho = new URL(endereco);  

// conexão  
try {
url = (HttpURLConnection) caminho.openConnection(proxy);  
url.setConnectTimeout(200000);  
url.connect();  
status = url.getResponseCode();  

System.out.println(status);  

} catch (SocketTimeoutException e1) {  
System.out.println("Tempo excedido.");  
}  

} catch (IOException e) {  
e.printStackTrace();  
} */
/*
if (args.length == 0) {
System.out.println("Não foi especificado nenhuma URL.");
// Fechando aplicação.
System.exit(1);
}

// Pegando a url passada como parametro.*/

/*URL url = new URL(urlName);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
System.out.println(url);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

String line = null;
System.out.println("1");
while( (line = in.readLine()) != null ){
System.out.println(line);
}

in.close();
urlConnection.disconnect();*/
